<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible"  :style="{ height: '80vh',width: '700px' }">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      class="advisor-form"
    >
<!--      <el-form-item label="C端用户id" prop="memberId">-->
<!--        <el-input v-model="formData.memberId" placeholder="请输入C端用户id" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="后管用户id" prop="userId">-->
<!--        <el-input v-model="formData.userId" placeholder="请输入后管用户id" />-->
<!--      </el-form-item>-->
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="formData.userName" placeholder="请输入顾问的真实姓名" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="formData.nickName" placeholder="请输入顾问的昵称" />
      </el-form-item>
      <el-form-item label="类型" prop="bizType">
        <el-select v-model="formData.bizType" placeholder="请选择类型">
          <el-option
            v-for="item in bizTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brand">
        <el-input v-model="formData.brand" placeholder="请输入品牌名称" />
      </el-form-item>
     

      <el-form-item label="擅长目的地" prop="destList">
        <el-tag
          v-for="dest in formData.destList"
          :key="dest.id"
          class="mr-2">
          {{dest.name}}
        </el-tag>
        
        <el-button
          plain
          v-model="formData.destList"
          @click="handleOpenDestinationListForm(formData.destList)"
        >
          选择目的地
        </el-button>
      </el-form-item>
      <el-form-item label="标签" prop="tagList">
        <div class="tag-container">
          <div class="selected-tags">
            <el-tag
              v-for="tag in formData.tagList"
              :key="tag.id || tag.desc"
              closable
              class="mr-2"
              @close="removeTag(tag)"
            >
              {{tag.desc}}
            </el-tag>
          </div>
          <el-button @click="openTagListForm" plain>选择标签</el-button>
        </div>
      </el-form-item>
      <el-form-item label="人设" prop="character">
        <el-select v-model="formData.character" placeholder="请选择人设" value-key="id">
          <el-option
            v-for="item in characterOptions"
            :key="item.id"
            :label="item.type + ' - ' + item.desc"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="个性化签名" prop="personality">
        <el-input v-model="formData.personality" placeholder="请输入个性化签名" />
      </el-form-item>
      <el-form-item label="核心亮点" prop="excellence">
        <el-input v-model="formData.excellence" placeholder="请输入核心亮点" />
      </el-form-item>
      <el-form-item label="亮点详情" prop="excellenceList">
        <div class="excellence-list">
          <div v-for="(item, index) in formData.excellenceList" :key="index" class="excellence-item">
            <div class="excellence-index">{{index + 1}}</div>
            <el-input v-model="item.desc" clearable placeholder="请输入亮点详情" class="excellence-input">
              <template #append>
                <el-button @click="removeExcellence(index)" type="danger" :icon="Delete"/>
              </template>
            </el-input>
          </div>
          <el-button @click="addExcellence" type="primary" plain :icon="Plus" class="add-excellence-btn">添加亮点</el-button>
        </div>
      </el-form-item>
      <el-form-item label="工作年限" prop="workingYears">
        <el-input v-model="formData.workingYears" placeholder="请输入顾问的工作年限" />
      </el-form-item>
      <el-form-item label="服务人数" prop="serviceGuestCount">
        <el-input v-model="formData.serviceGuestCount" placeholder="请输入服务人数" />
      </el-form-item>
      <el-form-item label="头像背景" class="avatar-background-form">
        <div class="avatar-background-container">
          <div class="avatar-container">
            <UserAvatar :img="formData.headPhoto" v-model:headPhoto="formData.headPhoto" />
          </div>
          <div class="background-container">
            <el-image
              style="cursor: pointer;"
              class="background-image"
              :src="formData.coverPhoto"
              @click="handleOpenBackgroundImageListForm"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="微信号" prop="wechat">
        <el-input v-model="formData.wechat" placeholder="请输入微信号" />
      </el-form-item>

      <el-form-item label="电话号码" prop="telephone">
        <el-input v-model="formData.telephone" placeholder="请输入电话号码" />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
      <el-input v-model="formData.longitude" placeholder="请输入经度，用于定位顾问的地理位置" />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
      <el-input v-model="formData.latitude" placeholder="请输入纬度，用于定位顾问的地理位置" />
      </el-form-item>
      <el-form-item label="携程openId" prop="openId">
        <el-input v-model="formData.openId" placeholder="请输入关联携程的openid" />
      </el-form-item>
      <el-form-item label="推荐人ID" prop="referrerId">
        <el-input v-model="formData.referenceId" placeholder="请输入推荐人ID" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input v-model="formData.storeName" placeholder="请输入店铺名称" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="顾问等级" prop="level">
        <el-input v-model="formData.level" placeholder="请输入顾问等级" />
      </el-form-item>
<!--      <el-form-item label="审核状态" prop="auditStatus">-->
<!--        <el-radio-group v-model="formData.auditStatus">-->
<!--          <el-radio-->
<!--            v-for="dict in getIntDictOptions(DICT_TYPE.GTA_ADVISOR_AUDIT_STATUS)"-->
<!--            :key="dict.value"-->
<!--            :value="dict.value"-->
<!--          >-->
<!--            {{ dict.label }}-->
<!--          </el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="注册来源" prop="source">-->
<!--        <el-input v-model="formData.source" placeholder="请输入注册来源" />-->
<!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <BackgroundImageListForm ref="backgroundImageListForm" @change="onBackgroundImageSelected" />
  <DestinationListForm ref="destinationListForm" @confirm="onDestinationSelected" />
  <TagListForm ref="tagListForm" @confirm="onTagsSelected" />
</template>
<script setup lang="ts">
import { AdvisorApi, AdvisorVO } from '@/api/gta/advisor'
// import { getIntDictOptions, DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import UserAvatar from "./UserAvatar.vue"
import BackgroundImageListForm from "./BackgroundImageListForm.vue"
import DestinationListForm from "./DestinationListForm.vue"
import { Delete, Plus } from '@element-plus/icons-vue'
import { TagTabs, StoreConfigData } from './constant'
import TagListForm from './TagListForm.vue'

/** 顾问信息 表单 */
defineOptions({ name: 'AdvisorForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 人设选项静态字典
const characterOptions = [
  { id: 1, type: "专家咖", desc: "品牌赛季传奇王者顾问" },
  { id: 2, type: "资源咖", desc: "社交高手人脉资源丰富" },
  { id: 3, type: "服务咖", desc: "贴心\"旅游管家\"式服务" },
  { id: 4, type: "高端咖", desc: "私人定制\"个性化\"旅游" },
  { id: 5, type: "创意咖", desc: "N个创意方式打卡新玩法" },
  { id: 6, type: "沟通咖", desc: "明确客户需求协调能力强" }
]

const bizTypeOptions = [
  { label: '门店', value: 1 },
  { label: '顾问', value: 2 },
  { label: '旅行社', value: 3 }
]

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<{
  id?: number
  memberId?: number
  userId?: number
  bizType?: number
  brand?: string
  openId?: string
  userName?: string
  nickName?: string
  destList: any[]
  tagList: any[]
  character?: any
  workingYears?: number
  personality?: string
  excellence?: string
  excellenceList: { desc: string }[]
  headPhoto?: string
  coverPhoto: string
  wechat?: string
  email?: string
  telephone?: string
  longitude?: number
  latitude?: number
  address?: string
  serviceGuestCount?: number
  outerId?: number
  referenceId?: number
  storeName?: string
  level?: number
  auditStatus?: number
  source?: number
}>({
  id: undefined,
  memberId: undefined,
  userId: undefined,
  bizType: undefined,
  brand: undefined,
  openId: undefined,
  userName: undefined,
  nickName: undefined,
  destList: [],
  tagList: [],
  character: undefined,
  workingYears: undefined,
  personality: undefined,
  excellence: undefined,
  excellenceList: [],
  headPhoto: undefined as string | undefined,
  coverPhoto: '',
  wechat: undefined,
  email: undefined,
  telephone: undefined,
  longitude: undefined,
  latitude: undefined,
  address: undefined,
  serviceGuestCount: undefined,
  outerId: undefined,
  referenceId: undefined,
  storeName: undefined,
  level: undefined,
  auditStatus: undefined,
  source: undefined
})
const formRules = reactive({
  // userName: [{ required: true, message: '顾问的真实姓名不能为空', trigger: 'blur' }],
  // auditStatus: [{ required: true, message: '审核状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const backgroundImageListForm = ref() // 背景图片选择表单
const destinationListForm = ref() // 选择目的地
const tagListForm = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await AdvisorApi.getAdvisor(id)
      
      
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 克隆数据，避免直接修改表单数据
    const data = { ...formData.value } as any
    
    // character已经是对象，不需要额外处理
    
    if (formType.value === 'create') {
      await AdvisorApi.createAdvisor(data)
      message.success(t('common.createSuccess'))
    } else {
      await AdvisorApi.updateAdvisor(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    memberId: undefined,
    userId: undefined,
    bizType: undefined,
    brand: undefined,
    openId: undefined,
    userName: undefined,
    nickName: undefined,
    destList: [],
    tagList: [],
    character: undefined,
    workingYears: undefined,
    personality: undefined,
    excellence: undefined,
    excellenceList: [],
    headPhoto: undefined as string | undefined,
    coverPhoto: '',
    wechat: undefined,
    email: undefined,
    telephone: undefined,
    longitude: undefined,
    latitude: undefined,
    address: undefined,
    serviceGuestCount: undefined,
    outerId: undefined,
    referenceId: undefined,
    storeName: undefined,
    level: undefined,
    auditStatus: undefined,
    source: undefined
  }
  formRef.value?.resetFields()
}

// 打开背影图片选择列表
const handleOpenBackgroundImageListForm = () => {
  backgroundImageListForm.value.open()
}

const onBackgroundImageSelected = (url: string) => {
  formData.value.coverPhoto = url
}

const handleOpenDestinationListForm = (destinations) => {
  destinationListForm.value.open(destinations)
}

const onDestinationSelected = (destinations: {id:string,name:string}[]) => {
  formData.value.destList = destinations
}

// 添加亮点
const addExcellence = () => {
  if (!formData.value.excellenceList) {
    formData.value.excellenceList = []
  }
  formData.value.excellenceList.push({ desc: '' })
}

// 删除亮点
const removeExcellence = (index: number) => {
  if (formData.value.excellenceList) {
    formData.value.excellenceList.splice(index, 1)
  }
}

// 打开标签选择表单
const openTagListForm = () => {
  tagListForm.value.open(formData.value.tagList)
}

// 移除标签
const removeTag = (tag: any) => {
  const index = formData.value.tagList.findIndex(t => 
    (tag.id ? t.id === tag.id && t.type === tag.type : t.desc === tag.desc)
  )
  if (index > -1) {
    formData.value.tagList.splice(index, 1)
  }
}

// 标签选择确认
const onTagsSelected = (tags: any[]) => {
  formData.value.tagList = tags
}

</script>

<style lang="scss" scoped>
.advisor-form {
  height: calc(80vh - 160px);
  overflow-y: auto;
  padding-right: 10px;
}

.background-image {
  max-width: 200px;
  max-height: 120px;
  object-fit: cover;
}

:deep(.el-dialog__body) {
  overflow: hidden;
  padding: 10px 20px;
}

.mr-2 {
  margin-right: 8px;
}

.avatar-background-form {
  :deep(.el-form-item__label) {
    height: 32px;
    line-height: 32px;
  }
}

.avatar-background-container {
  display: flex;
  gap: 32px;
  align-items: center;

  .avatar-container {
    display: flex;
    align-items: center;
  }

  .background-container {
    flex: 1;
  }

  .background-image {
    width: 200px;
    height: 120px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
  }
}

.excellence-list {
  .excellence-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;

    .excellence-index {
      min-width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background-color: #409EFF;
      color: white;
      border-radius: 50%;
      font-size: 14px;
    }

    .excellence-input {
      flex: 0 0 490px;
    }
  }

  .add-excellence-btn {
    margin-top: 8px;
  }
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 16px 0;

  .tag-item {
    cursor: pointer;
    
    &.is-selected {
      background-color: #409EFF;
      border-color: #409EFF;
      color: white;
    }
  }
}

.custom-tag-input {
  width: 100%;
  margin-bottom: 16px;
}
</style>
